package com.livegoods.service.impl;

import com.livegoods.pojo.Item;
import com.livegoods.pojo.LivegoodsResult;
import com.livegoods.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class ItemServiceImpl implements ItemService {

    @Value("${livegoods.fastdfs.nginx}")
    private String nginxHost;

    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public LivegoodsResult selectHotProduct(String city) {

        try {
            Criteria criteria = Criteria.where("city").is(city);
            Query query = new Query(criteria);
            query.with(PageRequest.of(0,4,Sort.by(Sort.Order.desc("sales"))));

            List<Item> items = mongoTemplate.find(query, Item.class);
            for (Item item : items) {
                item.setImg(nginxHost+item.getImg());
            }

            return LivegoodsResult.ok(items);
        } catch (Exception e) {
            return LivegoodsResult.error("服务器操作失败...");
        }
    }
}
